<template>
  <div
    class="r-chart-container"
    v-bind="$attrs"
    :style="{ aspectRatio: props.aspectRatio }"
    v-resize="props.resizeEnable ? onResize : null"
  >
    <div class="chart-box" ref="chartRef"></div>
  </div>
</template>

<script setup>
import { nextTick, onMounted, ref, toValue, watch } from 'vue';
import { init } from 'echarts';
import { useState, useDebounce } from '@/hooks/index.js';
import { useAppStore } from '@/store/index.js';

const { themeConfig } = useAppStore();

defineOptions({
  inheritAttrs: false
});

const props = defineProps({
  option: { type: Object, default: () => ({}), required: true },
  resizeEnable: { type: Boolean, default: true },
  resizeDelay: { type: Number, default: 200 },
  aspectRatio: { type: Number, default: 16 / 9 }
});

const chartRef = ref(null);
const [chart, setChart] = useState(null);

onMounted(() => {
  nextTick(() => setTimeout(initChart, 0));
});

const initChart = () => {
  const target = toValue(chartRef);
  const chart = init(target);
  const option = props.option;

  option.darkMode = option.darkMode ?? themeConfig.theme === 'dark';

  // 判断是否有grid配置，没有则默认配置
  const isGrid = !Object.hasOwn(option, 'grid');
  if (isGrid) {
    option.grid = {
      top: 16,
      bottom: 16,
      left: 16,
      right: 16,
      containLabel: true
    };
  }
  chart.setOption(option);
  setChart(chart);
};

watch(
  () => props.option,
  (val) => toValue(chart)?.setOption(val)
);

/*
 * 监听窗口变化
 *
 * 卡顿：待修复
 * 复现：浏览器宽度缩小，图表未能及时重新渲染，再此放大窗口，页面卡死
 * 原因：延时绘制，导致图表无法及时刷新 [防抖?]
 */
const onResize = useDebounce(async () => {
  toValue(chart)?.resize();
}, props.resizeDelay);
</script>

<style lang="scss" scoped>
.r-chart-container {
  width: 100%;
  aspect-ratio: 16/9;
  position: relative;

  .chart-box {
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    position: absolute;
    padding: 8px;
    overflow: hidden;
  }
}
</style>
